package library.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import library.dto.BookDTO;
import library.dto.Category_HighDTO;
import library.dto.Category_LowDTO;
import library.dto.Category_MiddleDTO;
import library.dto.MemberDTO;
import library.dto.ZipcodeDTO;
import library.model.service.LibraryService;
import library.util.Utilities;

import org.json.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LibraryController {

	private LibraryService service;

	public LibraryController(LibraryService service) {
		super();
		this.service = service;
	}
	
	//회원가입
	@RequestMapping("/registerMember.do")
	public ModelAndView registerMember(MemberDTO mdto, String hp1, String hp2, String hp3){
		System.out.println(hp1 +" : "+hp2+" : "+hp3);
		ModelAndView mv = null;
		mdto.setHp(hp1 + hp2 + hp3);
		mdto.setState_no(0);
		try {
			service.insertMember(mdto);
			mv = new ModelAndView("/login_form");
		} catch (Exception e) {
			e.printStackTrace();
			mv = new ModelAndView("/res/error", "error_message", e.getMessage());
		}
		return mv;
	}
	//아이디체크
	@RequestMapping("/idCheck.do")
	public void idcheck(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		String id = request.getParameter("id");
		response.setHeader("Cache-Control", "no-cache");
		System.out.println(id);
		String result = "no";
		try {
			MemberDTO mdto = service.selectMemberById(id);
			PrintWriter out = response.getWriter();
			if(mdto != null){ //비어있지않다면
				result = "yes";
			}
			out.println(result);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	//우편번호검색
	@RequestMapping("postCheck.do")
	protected void postCheck(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
				request.setCharacterEncoding("utf-8");
				response.setContentType("text/html;charset=utf-8");
				response.setHeader("Cache-Control", "no-cache");
				String dong = request.getParameter("dong");
				System.out.println(dong);
				try{
					ArrayList<ZipcodeDTO>  result = service.selectByDong(dong);
					JSONArray arr = new JSONArray(result);
					PrintWriter out = response.getWriter();
					out.println(arr);
				}catch(SQLException e){
					e.printStackTrace();
				}														    	
	}
	//아이디 분실시 찾기
	@RequestMapping("/searchId.do")
	protected void searchId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		String name = request.getParameter("name");
		String registerNumber1 = request.getParameter("registerNumber1");
		String registerNumber2 = request.getParameter("registerNumber2");
		System.out.println(name +" : " + registerNumber1  +" : " + registerNumber2);
		String result;
		try{
			MemberDTO mdto = service.selectMemberByRegisterNumber(name, registerNumber1, registerNumber2);
			if(mdto==null){
				result = "null";
			}else{
				result = mdto.getId();
			}
			PrintWriter out = response.getWriter();
			out.println(result);
		}catch(SQLException e){
			e.printStackTrace();
		}
	}
	//패스워드 분실시 찾기
		@RequestMapping("/searchPassword.do")
		protected void searchPassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			response.setHeader("Cache-Control", "no-cache");
			String id = request.getParameter("id");
			String registerNumber1 = request.getParameter("registerNumber1");
			String registerNumber2 = request.getParameter("registerNumber2");
			System.out.println(id +" : " + registerNumber1  +" : " + registerNumber2);
			String result;
			try{
				MemberDTO mdto = service.selectMemberByPassword(id, registerNumber1, registerNumber2);
				if(mdto==null){
					result = "null";
				}else{
					result = mdto.getPassword();
				}
				PrintWriter out = response.getWriter();
				out.println(result);
			}catch(SQLException e){
				e.printStackTrace();
			}
		}
	//전체회원조회 - ken
	@RequestMapping("/searchMemberByAll.do")
	public ModelAndView getAllMemberList(){
		ModelAndView mv = null;
		try {
			ArrayList<MemberDTO> list = service.getAllMemberList();
			mv = new ModelAndView("res/admin/member_list", "member_list", list);
		} catch (SQLException e) {
			e.printStackTrace();
			mv = new ModelAndView("res/error", "error_message", e.getMessage());
		}
		return mv;
	}
	//전체 책 목록 검색 - ken
		@RequestMapping("/searchBookAll.do")
		public ModelAndView searchBookAll(){
			ModelAndView mv = null;
			try {
				List list = service.searchBookAll();
				mv = new ModelAndView("jsonView", "list", list);
			} catch (Exception e) {
				e.printStackTrace();
				mv = new ModelAndView("res/error/error", "error_message", e.getMessage());
			}			
			return mv;
		}

	//ID로 회원 정보 조회 - ken
	@RequestMapping("/searchMemberId.do")
	public ModelAndView selectMemberById(String id){
		ModelAndView mv = null;
		ArrayList<MemberDTO> list = new ArrayList();
		try {
			MemberDTO mto = service.selectMemberById(id);
			list.add(mto);
			mv = new ModelAndView("res/admin/member_list", "member_list", list);
		} catch (SQLException e) {
			e.printStackTrace();
			mv = new ModelAndView("res/error", "error_message", e.getMessage());
		}
		return mv;
	}
	//사람이름으로 회원 정보 조회 -ken
	@RequestMapping("/searchMemberByName.do")
	public ModelAndView selectMemberByName(String name){
		ModelAndView mv = null;
		ArrayList<MemberDTO> list = new ArrayList();
		try {
			list = service.selectMemberByName(name);
			mv = new ModelAndView("res/admin/member_list", "member_list", list);
		} catch (SQLException e) {
			e.printStackTrace();
			mv = new ModelAndView("res/error", "error_message", e.getMessage());
		}
		return mv;
	}
	//대여한 책이름으로 회원 정보 조회 -ken
		@RequestMapping("/searchMemberByBook.do")
		public ModelAndView selectMemberByBookName(String book){
			ModelAndView mv = null;
			ArrayList<MemberDTO> list = new ArrayList();
			try {
				list = service.selectMemberByBook(book);				
				mv = new ModelAndView("res/admin/member_list", "member_list", list);
			} catch (SQLException e) {
				e.printStackTrace();
				mv = new ModelAndView("res/error", "error_message", e.getMessage());
			}
			return mv;
		}
		//회원상태로 회원 정보 조회 - ken
		@RequestMapping("/searchMemberByState.do")
		public ModelAndView selectMemberByState(int state){
			ModelAndView mv = null;
			ArrayList<MemberDTO> list = new ArrayList();
			try {
				list = service.selectMemberByState(state);
				mv = new ModelAndView("res/admin/member_list", "member_list", list);
			} catch (SQLException e) {
				e.printStackTrace();
				mv = new ModelAndView("res/error", "error_message", e.getMessage());
			}
			return mv;
		}

	//책 이름으로 책 목록 검색-Yong
	@RequestMapping("/searchBookByName.do")
	public ModelAndView searchBookByName(String name) throws Exception{
		ModelAndView mv = null;
		try {
			List list = service.searchBookByName(name);
			mv = new ModelAndView("res/searchBook/Search_list_byName", "search_list", list);
		} catch (Exception e) {
			e.printStackTrace();
			mv = new ModelAndView("res/error/error", "error_message", e.getMessage());
		}
		return mv;
	}
	
	//분류별로 검색(HighCategory) -Yong
	@RequestMapping("/searchBookByCategory.do")
	public ModelAndView searchBookByCategory() throws Exception{
		ModelAndView mv = null;				
		try {
			ArrayList<Category_HighDTO> list = (ArrayList)service.getAllHighCategory();
			mv = new ModelAndView("res/searchBook/Search_list_byCategory", "highCategory", list);
		} catch (Exception e) {
			e.printStackTrace();
			mv = new ModelAndView("res/error/error", "error_message", e.getMessage());
		}
		return mv;
	}
	//분류별로 검색(HighCategory)(jsonView) -ken
		@RequestMapping("searchBookByCategory2.do")
		public ModelAndView searchBookByCategory2(){
			ModelAndView mv = null;				
			try {
				ArrayList<Category_HighDTO> list = (ArrayList)service.getAllHighCategory();
				mv = new ModelAndView("jsonView", "list", list);
			} catch (Exception e) {
				e.printStackTrace();
				mv = new ModelAndView("res/error/error", "error_message", e.getMessage());
			}
			return mv;
		}
	
	//분류별로 검색(MiddleCategory) - Yong
	@RequestMapping("/category_high.do")
	public void searchBookByMiddleCategory(HttpServletRequest request,HttpServletResponse response,String CategoryHighId) throws Exception{
		try {
			response.setContentType("text/html;charset=utf-8");
			response.setHeader("Cache-Control", "no-cache");
			ArrayList list = (ArrayList)service.getAllMiddleCategory(CategoryHighId);
			JSONArray jarr = new JSONArray(list);
			PrintWriter out = response.getWriter();
			out.println(jarr);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//분류별로 검색(MiddleCategory)(jsonView) -ken
			@RequestMapping("searchBookByMiddleCategory.do")
			public ModelAndView searchBookByMiddleCategory(String categoryHighId){
				ModelAndView mv = null;				
				System.out.println(categoryHighId);
				try {
					ArrayList<Category_MiddleDTO> list = (ArrayList)service.getAllMiddleCategory(categoryHighId);
					mv = new ModelAndView("jsonView", "list", list);
				} catch (Exception e) {
					e.printStackTrace();
					mv = new ModelAndView("res/error/error", "error_message", e.getMessage());
				}
				return mv;
			}
	
	//분류별로 검색(LowCategory) - Yong
	@RequestMapping("/category_middle.do")
	public void searchBookByLowCategory(HttpServletRequest request, HttpServletResponse response, String categoryMiddleId) throws Exception{
		try {
			response.setContentType("text/html;charset=utf-8");
			response.setHeader("Cache-Control", "no-cache");
			ArrayList list = (ArrayList)service.getAllLowCategory(categoryMiddleId);
			JSONArray jarr = new JSONArray(list);
			PrintWriter out = response.getWriter();
			out.println(jarr);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//분류별로 검색(lowCategory)(jsonView) -ken
	@RequestMapping("searchBookByLowCategory.do")
	public ModelAndView searchBookByLowCategory(String categoryLowId){
		ModelAndView mv = null;
		System.out.println(categoryLowId);
		try {
			ArrayList<Category_LowDTO> list = (ArrayList)service.getAllLowCategory(categoryLowId);
			for(Category_LowDTO dto:list){
				System.out.println(dto.getCategory_Low_Id());
				System.out.println(dto.getCategory_Low_Name());
			}
			mv = new ModelAndView("jsonView", "list", list);
		} catch (Exception e) {
			e.printStackTrace();
			mv = new ModelAndView("res/error/error", "error_message", e.getMessage());
		}
		return mv;
	}
	
	//분류별로 검색후 검색 결과(BookListByCategory) - Yong
	@RequestMapping("/getBookByCategory.do")
	public void searchBookListByCategory(HttpServletRequest request, HttpServletResponse response, String CategoryLowId) throws Exception{
		try {
			response.setContentType("text/html;charset=utf-8");
			response.setHeader("Cache-Control", "no-cache");
			ArrayList list = (ArrayList)service.getBookListByCategory(CategoryLowId);
			JSONArray jarr = new JSONArray(list);
			PrintWriter out = response.getWriter();
			System.out.println(jarr.toString());
			out.println(jarr);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//분류별로 검색후 검색 결과(BookListByCategory)(jsonView) -ken
	@RequestMapping("searchBookListByCategory.do")
	public ModelAndView searchBookListByCategory(String categoryLowId){
		ModelAndView mv = null;
		System.out.println(categoryLowId);
		try {
			ArrayList list = (ArrayList)service.getBookListByCategory(categoryLowId);
			mv = new ModelAndView("jsonView", "list", list);
		} catch (Exception e) {
			e.printStackTrace();
			mv = new ModelAndView("res/error/error", "error_message", e.getMessage());
		}
		return mv;
	}

	//신착도서 결과 검색(7일 이내) - Yong
	@RequestMapping("/searchBookByInputDate.do")
	public ModelAndView searchBookListByInputDate() throws Exception{
		ModelAndView mv = null;
		String nowDate = Utilities.changeDateFormat(Utilities.getNow());
		int intDate = Integer.parseInt(nowDate);
		String aDate = String.valueOf(intDate-7);
		String aDateMonth = String.valueOf(intDate-76);
		String aDateYear = String.valueOf(intDate-8876);
		HashMap map = new HashMap();
		if(nowDate.substring(0, 6).equals(aDate.substring(0, 6))){
			map.put("nDate", nowDate);
			map.put("aDate", aDate);
		}else if(nowDate.substring(0, 4).equals(aDateMonth.substring(0, 4))){
			map.put("nDate", nowDate);
			map.put("aDate", aDateMonth);
		}else{
			map.put("nDate", nowDate);
			map.put("aDate", aDateYear);
		}
		try {
			List list = service.searBookByInputDate(map);
			mv = new ModelAndView("res/searchBook/Search_list_byInputdate", "search_list", list);
		} catch (Exception e) {
			e.printStackTrace();
			mv = new ModelAndView("res/error/error", "error_message", e.getMessage());
		}
		return mv;
		
	}
	//인기 도서 검색 - Yong (지금은 5개로 설정 library.xml)에서 5를 10으로 바꾸면 10개로 바뀜
	@RequestMapping("/searchBookByCount.do")
	public ModelAndView searchBookByCound() throws Exception{
		ModelAndView mv = null;
		String nowDate = Utilities.changeDateFormat(Utilities.getNow());
		int intDate = Integer.parseInt(nowDate);
		String aDateMonth = String.valueOf(intDate-100);
		HashMap map = new HashMap();
		map.put("nDate", nowDate);
		map.put("aDate", aDateMonth);
		try {
			List list = service.searchBookByCount(map);
			mv = new ModelAndView("res/searchBook/Search_list_byCount", "search_list", list);
		} catch (Exception e) {
			e.printStackTrace();
			mv = new ModelAndView("res/error/error", "error_message", e.getMessage());
		}
		return mv;
		
	}

	//SN로 책 목록 검색 - ken
	@RequestMapping("/searchBookBySN.do")
	public ModelAndView searchBookBySN(String sn){
		ModelAndView mv = null;
		try {
			BookDTO bdto = service.searchBookBySN(sn);
			ArrayList list = new ArrayList();
			list.add(bdto);
			mv = new ModelAndView("jsonView", "list", list);
		} catch (Exception e) {
			e.printStackTrace();
			mv = new ModelAndView("res/error/error", "error_message", e.getMessage());
		}
		
		return mv;
	}

	//로그인
	@RequestMapping("/login.do")
	public ModelAndView login(String id, String password, HttpSession session){
		ModelAndView mv = null;
		try{
			MemberDTO mto = service.selectMemberById(id);
			if(mto!=null){
				//패스 워드 비교
				if(password.equals(mto.getPassword())){//ID/Password 모두 맞는 경우
					session.setAttribute("login_info", mto);
					mv = new ModelAndView("res/login_success");
				}else{//패스워드가 틀린 경우
					mv = new ModelAndView("login_form", "error_message","패스워드가 틀렸습니다. 확인 후 다시 로그인 하세요.");
				}
			}else{//id가 없는 경우
				mv = new ModelAndView("login_form", "error_message",  id+"는 없는 ID입니다. 확인 후 다시 로그인 하세요.");
			}
		} catch (SQLException e) {
			e.printStackTrace();
			mv = new ModelAndView("res/error", "error_message", e.getMessage());
		}
		return mv;
	}
		//로그아웃
		@RequestMapping("/logout.do")
		public ModelAndView logout(HttpSession session) throws Exception{
			ModelAndView mv = null;
			MemberDTO mdto = (MemberDTO)session.getAttribute("login_info");
			if(mdto==null){
				mv = new ModelAndView("login_form", "error_message", "이미 안전하게 로그아웃 되었습니다.");
			}else{
				session.invalidate();
				mv = new ModelAndView("login_form", "logout_message","로그아웃 되셨습니다. 이용해주셔서 감사합니다.");
			}
			return mv;
		}
		//회원탈퇴
		@RequestMapping("/removeMember.do")
		public ModelAndView removeMember(HttpSession session)throws Exception{
			ModelAndView mv = null;
			MemberDTO loginInfo = (MemberDTO)session.getAttribute("login_info");
			if(loginInfo == null){//로그인 안된 경우
				mv = new ModelAndView("login_form", "error_message", "로그인 후 탈퇴가 가능합니다.");
			}else{
				try {
					service.removeMemberById(loginInfo);
					mv = new ModelAndView("login_form","remove_message","정상적으로 탈퇴 처리가 되었습니다.");
//					세션 소멸시키기
					session.invalidate();
				}catch (SQLException e) {
					e.printStackTrace();
					mv = new ModelAndView("res/error", "error_message", e.getMessage());
				} 
			}
			return mv;
		}

	//책 이름으로 책 목록 검색(jsonView) - ken
		@RequestMapping("/searchBookByName2.do")
		public ModelAndView searchBookByName2(String name){
			System.out.println(name);
			ModelAndView mv = null;
			try {
				List list = service.searchBookByName(name);
				mv = new ModelAndView("jsonView", "list", list);
			} catch (Exception e) {
				e.printStackTrace();
				mv = new ModelAndView("res/error/error", "error_message", e.getMessage());
			}
			return mv;
		}
		//저자로 책 목록 검색 - ken
		@RequestMapping("/searchBookByWriter.do")
		public ModelAndView searchBookByWriter(String writer){
			ModelAndView mv = null;
			try {
				List list = service.searchBookByWriter(writer);
				mv = new ModelAndView("jsonView", "list", list);
			} catch (Exception e) {
				e.printStackTrace();
				mv = new ModelAndView("res/error/error", "error_message", e.getMessage());
			}
			return mv;
		}

		//상태로 책 목록 검색 - ken
		@RequestMapping("/searchBookByState.do")
		public ModelAndView searchBookByState(int state){
			ModelAndView mv = null;
			try {
				List list = service.searchBookByState(state);
				mv = new ModelAndView("jsonView", "list", list);
			} catch (Exception e) {
				e.printStackTrace();
				mv = new ModelAndView("res/error/error", "error_message", e.getMessage());
			}
			return mv;
		}
		
		//도서 정보 수정(sn으로) - ken
		@RequestMapping("/bookModify.do")
		public ModelAndView bookModify(String sn){
			ModelAndView mv = null;
			BookDTO bdto = service.searchBookBySN(sn);
			try {
				mv = new ModelAndView("res/admin/admin_book_manager_modify", "bdto", bdto);
			} catch (Exception e) {
				e.printStackTrace();
				mv = new ModelAndView("res/error/error", "error_message", e.getMessage());
			}
			return mv;
		}
		//회원상세페이지(대여/예약/희망도서 리스트)
		@RequestMapping("/getLoginMemberInfo.do")
		public ModelAndView getMemberBookList(HttpSession session) {
			MemberDTO mto = (MemberDTO)session.getAttribute("login_info");
			ModelAndView mv = null;
			if(mto==null){
				mv = new ModelAndView("login_form" , "error_message", "로그인 후 사용할 수 있습니다.");
			}else{
				HashMap map = new HashMap();
				try {
					map = service.getMemberBookList(mto.getId());
					session.setAttribute("book_list", map);
					mv = new ModelAndView("res/member/member_detail");
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}	
			return mv;
		}
		//회원정보 수정시 로그인 유무판단
		@RequestMapping("/modifyForm.do")
		public ModelAndView modifyForm(HttpSession session){
			MemberDTO mto = (MemberDTO)session.getAttribute("login_info");
			ModelAndView mv = null;
			if(mto==null){
				mv = new ModelAndView("login_form" , "error_message", "로그인 후 수정 할 수 있습니다. 로그인 먼저 하세요");
			}else{
				mv = new ModelAndView("res/member/member_modify");
			}	
			return mv;
		}
		//회원정보 수정
		@RequestMapping("/modifyMember.do")
		public ModelAndView modifyMember(MemberDTO mto,String hp1, String hp2, String hp3, HttpSession session){
			MemberDTO login_info = (MemberDTO)session.getAttribute("login_info");
			String hp = hp1 + hp2 + hp3;
			ModelAndView mv = null;
			if(login_info==null){
				mv = new ModelAndView("login_form" , "error_message", "로그인 후 수정 할 수 있습니다. 로그인 먼저 하세요");
			}else{
				try{
					mto.setHp(hp);
					service.updateMember(mto, login_info);
					login_info.setPassword(mto.getPassword());
					login_info.setHp(hp);
					login_info.setEmail(mto.getEmail());
					login_info.setZipcode(mto.getZipcode());
					login_info.setAddress1(mto.getAddress1());
					login_info.setAddress2(mto.getAddress2());
					login_info.setPictureFilename(mto.getPictureFilename());
					mv = new ModelAndView("res/login_success");
				}catch (SQLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}	
			}	
			return mv;
		}

}